package main

import (
	"bufio"
	"fmt"
	"os"
	"os/signal"
	"syscall"
	"time"
)

func main() {
	// 设置信号处理
	c := make(chan os.Signal, 1)
	signal.Notify(c, os.Interrupt, syscall.SIGTERM)
	go cleanupOnExit()

	// 获取出生日期
	birthday := getBirthDate()

	// 初始化终端显示
	initTerminal()
	defer restoreTerminal()

	// 主显示循环
	displayLoop(birthday)
}

// 获取出生日期
func getBirthDate() time.Time {
	reader := bufio.NewReader(os.Stdin)
	hideCursor()
	defer showCursor()

	for {
		clearScreen()
		fmt.Print("请输入您的出生日期 (YYYY-MM-DD): ")
		input, _ := reader.ReadString('\n')

		birthday, err := time.ParseInLocation("2006-01-02\n", input, time.Local)
		if handleDateError(err, birthday) {
			continue
		}

		return birthday
	}
}

// 时间计算逻辑
func calculateDuration(birthday time.Time) (days, hours, minutes, seconds int) {
	duration := time.Since(birthday)
	totalSeconds := int(duration.Seconds())

	seconds = totalSeconds % 60
	totalMinutes := totalSeconds / 60
	minutes = totalMinutes % 60
	totalHours := totalMinutes / 60
	hours = totalHours % 24
	days = totalHours / 24

	return days, hours, minutes, seconds
}

// 显示循环
func displayLoop(birthday time.Time) {
	for {
		days, hours, minutes, seconds := calculateDuration(birthday)
		updateDisplay(birthday, days, hours, minutes, seconds)
		time.Sleep(200 * time.Millisecond)
	}
}

// 显示界面
func updateDisplay(birthday time.Time, d, h, m, s int) {
	clearScreen()
	moveCursorTop()

	fmt.Printf(" 生日: \033[36m%s\033[0m\n\n", birthday.Format("2006-01-02"))
	fmt.Println(" 您已经活了：")
	fmt.Printf(" \033[33m%6d\033[0m 天 \033[34m%2d\033[0m 小时 \033[32m%2d\033[0m 分钟 \033[31m%2d\033[0m 秒\n", d, h, m, s)
	fmt.Println("\n\n 按 Ctrl+C 退出")
}

// 错误处理
func handleDateError(err error, t time.Time) bool {
	if err != nil {
		fmt.Print("\033[31m错误：日期格式无效！\033[0m")
		time.Sleep(1 * time.Second)
		return true
	}
	if t.After(time.Now()) {
		fmt.Print("\033[31m错误：未来日期不可用！\033[0m")
		time.Sleep(1 * time.Second)
		return true
	}
	return false
}

// 终端控制函数
func initTerminal() {
	hideCursor()
	clearScreen()
}

func restoreTerminal() {
	showCursor()
	clearScreen()
}

func cleanupOnExit() {
	<-make(chan os.Signal, 1)
	restoreTerminal()
	os.Exit(0)
}

// ANSI控制码
func hideCursor()    { fmt.Print("\033[?25l") }
func showCursor()    { fmt.Print("\033[?25h") }
func clearScreen()   { fmt.Print("\033[2J") }
func moveCursorTop() { fmt.Print("\033[H") }
